var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//express-jwt：用来验证token是否有效的中间件
var jwt = require("express-jwt");
var token = require("./util/token");

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var listensRouter = require('./routes/listens');

var app = express();

/**使用express-jwt中间件,查看express-jwt的版本号，npm list express-jwt
 * 7以下的版本调用jwt()，7以上的版本调用jwt.expressjwt()
 */
app.use(jwt.expressjwt({
  secret: "111",//token密钥
  algorithms: ["HS256"],//数字签名算法，默认HS256
}).unless({//白名单:不需要验证的token就可以访问的路由
  path: ["/users/login","/users/adminLogin", "/", "/users/regist", /^\/listens\//, /^\/images\//, /^\/musics\//,
    /^\/singers\//, /^\/songListImg\//,/^\/newusers\//]
}))

//定义拦截器，验证token是否有效
app.use((req, res, next) => {
  //客户端在得到服务器签发的token后，每一次请求都要手动将token添加到请求报文的authorization字段中.
  //获取请求报文头部的token
  let t = req.headers["authorization"];
  //解析token
  if (t) {
    //解析token
    token.getToken(t).then(data => {
      req.data = data;
      return next();
    }).catch((err) => {
      return next();
    })
  } else {
    return next();
  }
});

//错误中间件,在token失效时返回信息
app.use((err, req, res, next) => {
  if (err.status == 401) {
    res.send({ code: 401, msg: "token失效", data: {} });
  }
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use("/listens", listensRouter);
app.use('/users', usersRouter);


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
